#include "FileWriters.h"
#include<string.h>
#include<stdio.h>

//Default constructor
PPMFileWriter::PPMFileWriter(){}

//Initialization
PPMFileWriter::PPMFileWriter(char* filename, int w, int h)
{
	//open a file
	//first in text mode
	//to add the header
	ofile.open(filename);
	width = w;
	height = h;
	//strcpy(filepath, filename);
	filepath = filename;
	
	//write header to file
	if(ofile.good())
	{
		ofile<<"P6\n";
		ofile<<width<<" "<<height<<"\n";
		ofile<<"255 ";
	}
	//close the file
	ofile.close();
	//allocate enough memory for buffer 3*width*height
	buffer = new unsigned char[3*width*height];
}

//Put pixel function
//This function writes R,G,B values equal to color resulting in a gray scale image
void PPMFileWriter::PutPixel(int x, int y, unsigned char color)
{
	//assign three pixels continuously with color values
	buffer[x*width+y] = color;
	buffer[x*width+y+1] = color;
	buffer[x*width+y+2] = color;
}

//Write file function
//THis function writes contents of buffer into the file
void PPMFileWriter::WriteFile()
{
	//open file in binary mode
	ofile.open(filepath, std::ios::binary|std::ios::app);
	//write contents of buffer
	for(int i = 0 ; i < 3*width*height; i++)
	{
		ofile<<buffer[i];
	}
	//close file
	ofile.close();
}

//Copy image buffer
//This function copies any input buffer to image buffer
//care must be made sure that enough memory is available
bool PPMFileWriter::CopyImageBuffer(unsigned char* src_buffer, size_t buffer_size)
{
	if(buffer_size != 3*width*height)
	{
		//not of same size
		//return false
		return false;
	}
	else
	{
		//now copy contents
		memcpy(buffer, src_buffer, buffer_size);
		return true;
	}
}

//Copy Image buffer
//This function takes a color buffer as input parameter and fills in the image's default buffer
//the buffers should of be the same size - images width and height
bool PPMFileWriter::CopyImageBuffer(Color3* color_buffer, size_t buffer_size, float gamma)
{
	if(buffer_size != width*height) 
	{ 
		//buffers are of not the same size. 
		// we cannot copy. return false
		return false;
	}
	else
	{
		//convert the buffer to character
		//assuming gamma correction is explicitly specified we gamma correct it here
		if(gamma != 1.0f)
		{
			for(int i = 0; i < width*height; i++)
			{
				//gamma correct the image buffer
				color_buffer[i].GammaCorrect(gamma);
			}
		}
		
		// gamma conversion done
		//convert to unsigned char as it is
		//RGB255 temp;
		int index = 0;
		for(int i = 0; i < width*height; i++)
		{
			RGB255* temp = new RGB255;
			*temp = color_buffer[i].GetRGB255();
			//put those in images buffer
			buffer[index++] = temp->r;
			buffer[index++] = temp->g;
			buffer[index++] = temp->b;
			delete temp;
		}

		//all done
		return true;
	}
}


//Destructor
PPMFileWriter::~PPMFileWriter()
{
	delete[] buffer;
}
